<script setup>
import ResultWrapper from "@/views/restapi/ResultWrapper.vue";
import ParamDefine from "@/views/restapi/ParamDefine.vue";
import HeaderConfig from "@/views/restapi/HeaderConfig.vue";
import ProcessRelationConfig from "@/views/process/ProcessRelationConfig.vue";
import restApi from "@/api/rest/restApi";
import {nanoid} from "nanoid";
import {message} from 'ant-design-vue'
import $bus from '@/utils/mitt.js'

$bus.on('apiReloadJsonEvent', (car) => {
		console.log(car)
		apiDetailModel.value =car
		versionList.value =[car]
		reloadApiJson(versionList.value)
	})
const bizId = ref();
const processRelationVisible = ref(false);
const versionList = ref([]);
const activeVersion = ref();

const apiDetailModel = ref({
	apiTypeCode: null,
	protocolTypeCode: null,
	apiName: null,
	loginValidFlag:false,
	contextPath: null,
	apiCode: null
});

onMounted(async () => {
	await init(props.id);
})
const init = async (id) => {
	//先查一下
	const result = await restApi.queryApiById(id);

	const versions = await restApi.queryApiVersionList(id);

	if (versions) {
		versionList.value = versions;
	}
	if (!versionList.value) {
		versionList.value = [];
	}
	apiDetailModel.value = result;
	// if (apiDetailModel.value.methods) {
	// 	apiDetailModel.value.methods = JSON.parse(apiDetailModel.value.methods);
	// }

	if (apiDetailModel.value.resultWrapperConfig) {
		const cb = JSON.parse(apiDetailModel.value.resultWrapperConfig);
		apiDetailModel.value.sourceFieldDefine = cb.sourceFieldDefine;
		apiDetailModel.value.targetFieldDefine = cb.targetFieldDefine;
	}
	if (!apiDetailModel.value.sourceFieldDefine) {
		apiDetailModel.value.sourceFieldDefine = {
			params: [],
			isArrayFlag: false,
			isViewBasicFieldFlag: false,
			isAddColumnFlag: false,
			isUpdateColumnFlag: false,
			isRemoveColumnFlag: false,
			isAddChildrenColumnFlag: false,
			isMappingColumnFlag: true,
			isActionColumnFlag: true,
			isViewArrayFlag: false,
			basicTypeFlag: false,
			basicFieldType: false
		}
	}


	if (!apiDetailModel.value.targetFieldDefine) {
		apiDetailModel.value.targetFieldDefine = {
			params: [],
			isArrayFlag: false,
			isViewBasicFieldFlag: false,
			isViewArrayFlag: false,
			isMappingColumnFlag: true,
			isActionColumnFlag: true,
			basicTypeFlag: false,
			basicFieldType: false
		}
	}

	if (!apiDetailModel.value.resultWrapperFlag) {
		apiDetailModel.value.resultWrapperFlag = false;
	}


	if (versionList.value.length <= 0) {
		return
	}


	reloadApiJson(versionList.value)
}
const reloadApiJson = (versionList)=>{

	for (const version of versionList) {
		initVersion(version);
	}

	activeVersion.value = versionList[0].apiVersion;
}


const setVersionLatest = async (apiVersion) => {


	if (apiVersion.latestFlag) {

		if (apiVersion.id) {
			await restApi.updateApiVersionLatestFlag(apiVersion.id, false);
		}

		apiVersion.latestFlag = false;
	} else {
		if (apiVersion.id) {
			await restApi.updateApiVersionLatestFlag(apiVersion.id, true);
		}
		apiVersion.latestFlag = true;

		for (const v of versionList.value) {
			if (v.id == apiVersion.id) {
				continue
			}
			v.latestFlag = false;
		}
	}
}

const protocolTypeCodeList = ref([
	{
		name: "http",
		code: "http"
	}, {
		name: "https",
		code: "https"
	}
])


const apiTypeCodeList = ref([
	{
		name: "REST",
		code: "REST"
	}
]);

const methodList = ref([
	{
		name: "GET",
		code: "GET"
	}, {
		name: "POST",
		code: "POST"
	}, {
		name: "PUT",
		code: "PUT"
	}, {
		name: "OPTION",
		code: "OPTION"
	},
	{
		name: "DELETE",
		code: "DELETE"
	}
]);

const props = defineProps(['id'])
const relationProcess = () => {
	if (!apiDetailModel.value.id) {
		return;
	}
	bizId.value = apiDetailModel.value.id;
	processRelationVisible.value = true;

}


const updateApi = async () => {
	apiDetailModel.value.versionList = versionList.value;
	const params = JSON.parse(JSON.stringify(apiDetailModel.value));
	if (!params.id) {
		return
	}

	for (const cp of params.versionList) {

		if (cp.input) {
			if (cp.input.params) {
				cp.entity.inputParam = JSON.stringify(cp.input.params);
			}
			cp.entity.inputParamArrayFlag = cp.input.isArrayFlag;
			cp.entity.inputBasicFieldType = cp.input.basicFieldType;
			cp.entity.inputParamBasicTypeFlag = cp.input.basicTypeFlag;
		}
		if (cp.output) {
			if (cp.output.params) {
				cp.entity.resultParam = JSON.stringify(cp.output.params);
			}
			cp.entity.resultParamArrayFlag = cp.output.isArrayFlag;
			cp.entity.resultBasicFieldType = cp.output.basicFieldType;
			cp.entity.resultParamBasicTypeFlag = cp.output.basicTypeFlag;
		}
	}


	params.resultWrapperConfig = JSON.stringify({
		sourceFieldDefine: apiDetailModel.value.sourceFieldDefine,
		targetFieldDefine: apiDetailModel.value.targetFieldDefine
	});


	// if (params.methods && params.methods.length > 0) {
		// params.methods = JSON.stringify(params.methods)
	// }
	await restApi.updateApiById(params);

	message.info("保存成功")
	// console.log(JSON.parse(JSON.stringify(apiDetailModel.value)))
}


const handleTabsEdit = (targetName, action) => {
	if (action == 'add') {
		const version = nanoid(5);
		const newTabName = `${version}`;
		const cb = {
			apiVersion: newTabName
		};
		initVersion(cb);
		versionList.value.push(cb)

		activeVersion.value = newTabName;
	} else if (action === 'remove') {
		const tabs = versionList.value
		let activeName = activeVersion.value
		if (activeName === targetName) {
			tabs.forEach((tab, index) => {
				if (tab.apiVersion === targetName) {
					const nextTab = tabs[index + 1] || tabs[index - 1]
					if (nextTab) {
						activeName = nextTab.apiVersion
					}
				}
			})
		}

		activeVersion.value = activeName
		versionList.value = tabs.filter((tab) => tab.apiVersion !== targetName)
	}
}


const initVersion = (version) => {
	if (!version.entity) {
		version.entity = {};
	} else {
		version.input = {};
		version.input.params = JSON.parse(version.entity.inputParam);
		version.input.isArrayFlag = version.entity.inputParamArrayFlag;
		version.input.basicTypeFlag = version.entity.inputParamBasicTypeFlag;
		version.input.basicFieldType = version.entity.inputBasicFieldType;

		version.output = {};
		version.output.params = JSON.parse(version.entity.resultParam);
		version.output.isArrayFlag = version.entity.resultParamArrayFlag;
		version.output.basicTypeFlag = version.entity.resultParamBasicTypeFlag;
		version.output.basicFieldType = version.entity.resultBasicFieldType;
	}
	if (!version.headers) {
		version.headers = [];
	}

	// setDefaultValue();
	if (!version.input) {
		version.input = {
			isArrayFlag: false,
			basicTypeFlag: false,
			basicFieldType: null,
			params: []
		};
	}
	if (!version.output) {
		version.output = {
			isArrayFlag: false,
			basicTypeFlag: false,
			basicFieldType: null,
			params: []
		};
	}
}
</script>

<template>
	<a-card class="mb-2">
		<a-row justify="left">
			<a-col :span="5">
				<a-tag class="ml-2" type="success">{{ apiDetailModel?.apiName }}</a-tag>
			</a-col>
			<a-col :span="5">
				<a-tag class="ml-2" type="info">{{ apiDetailModel?.apiCode }}</a-tag>
			</a-col>
			<a-col :span="10">
			</a-col>
			<a-col :span="4">
				<a-space>
					<a-button @click="relationProcess">关联流程</a-button>
					<a-button type="primary" @click="updateApi">保存</a-button>
				</a-space>

			</a-col>
		</a-row>
	</a-card>


	<a-card class="mb-2">
		<a-row justify="start">
			<a-col :span="24">
				<a-tag class="ml-2" type="success">{{ apiDetailModel.description }}</a-tag>
			</a-col>
		</a-row>

	</a-card>

	<a-card class="mb-2">
		<a-row justify="start">

			<a-col :span="4">
				<a-space>
						<span>
							api类型：
						</span>
					<a-select v-model:value="apiDetailModel.apiTypeCode" class="m-2" placeholder="Select" size="large">
						<a-select-option v-for="item in apiTypeCodeList" :key="item.code" :label="item.name"
										 :value="item.code"/>
					</a-select>
				</a-space>
			</a-col>
			<a-col :span="5">
				<a-space>
						<span>
							协议类型：
						</span>
					<a-select v-model:value="apiDetailModel.protocolTypeCode" class="m-2" placeholder="Select"
							  size="large">
						<a-select-option v-for="item in protocolTypeCodeList" :key="item.code" :label="item.name"
										 :value="item.code"/>
					</a-select>
				</a-space>


			</a-col>

			<a-col :span="5">
				<a-space>
						<span>
							method：
						</span>
					<a-select v-model:value="apiDetailModel.methods" class="m-2" multiple placeholder="Select"
							  size="large">
						<a-select-option v-for="item in methodList" :key="item.code" :label="item.name"
										 :value="item.code"/>
					</a-select>
				</a-space>


			</a-col>
			<a-col :span="5">
				<a-space>
						<a-checkbox v-model:checked="apiDetailModel.loginValidFlag">是否登陆校验</a-checkbox>
				</a-space>


			</a-col>
		</a-row>
	</a-card>


	<a-card class="mb-2">
		<a-row justify="start">

			<a-col :span="6">
				<a-space>
						<span>
							host：
						</span>
					<a-input v-model:value="apiDetailModel.host" placeholder="请输入host"></a-input>
				</a-space>
			</a-col>
			<a-col :span="7">
				<a-space>
						<span>
							contextPath：
						</span>
					<a-input v-model:value="apiDetailModel.contextPath" placeholder="请输入contextPath"></a-input>
				</a-space>
			</a-col>
			<a-col :span="5">
				<a-space>
						<span>
							path：
						</span>
					<a-input v-model:value="apiDetailModel.path" placeholder="请输入path"></a-input>
				</a-space>
			</a-col>
		</a-row>
	</a-card>

	<a-card class="mb-2">
		<a-row justify="start">
			<a-col :span="24">
				<a-tabs v-model:activeKey="activeVersion">
					<a-tab-pane v-bind:key="version.apiVersion" v-for="version in versionList">
						<template #tab>
							<a-space>
									<span class="custom-tabs-label">
										<a-space>
											<span>{{ version.apiVersion }}</span>
											<a-button type="primary" @click="setVersionLatest(version)"
													  shape="circle">{{
													version.latestFlag ? 'unlatest' : 'latest'
												}}</a-button>
										</a-space>
									</span>
								<span class="custom-tabs-label">
										<CloseOutlined @click="handleTabsEdit(version.apiVersion, 'remove')"/>
									</span>
							</a-space>
						</template>
						<a-row justify="start">
							<a-col :span="1">
								<a-tag class="ml-2" type="success">headers</a-tag>
							</a-col>
						</a-row>
						<a-row>
							<a-col :span="24">
								<HeaderConfig :params="version"></HeaderConfig>
							</a-col>
						</a-row>


						<a-row justify="start" style="margin-top: 10px">
							<a-col :span="12">
								<a-row justify="start" class="mb-2">
									<a-col :span="2">
										<a-tag class="ml-2" type="success">输入</a-tag>
									</a-col>
								</a-row>
								<a-row>
									<a-col :span="24">
										<ParamDefine :params="version.input" :isViewBasicFieldFlag="true"
													 :isViewArrayFlag="true"
													 :isActionColumnFlag="true"
													 :isRemoveColumnFlag="true">
										</ParamDefine>
									</a-col>
								</a-row>
							</a-col>

							<a-col :span="12">
								<a-row justify="start" class="mb-2">
									<a-col :span="2">
										<a-tag class="ml-2" type="success">输出</a-tag>
									</a-col>
								</a-row>

								<a-row>
									<a-col :span="24">
										<ParamDefine :params="version.output" :isViewBasicFieldFlag="true"
													 :isViewArrayFlag="true">
										</ParamDefine>
									</a-col>
								</a-row>
							</a-col>
						</a-row>

					</a-tab-pane>

					<template #rightExtra>
						<PlusCircleOutlined @click="handleTabsEdit('dd', 'add')"/>
					</template>

				</a-tabs>


			</a-col>
		</a-row>
	</a-card>

	<a-card>
		<a-row justify="start">
			<a-col :span="24">
				<ResultWrapper :entity="apiDetailModel"></ResultWrapper>
			</a-col>
		</a-row>

	</a-card>
	<a-modal v-model:open="processRelationVisible" :closable="false" width="1000px">
		<ProcessRelationConfig :repationParamOpenFlag="false" :biz-id="bizId" biz-type="API">
		</ProcessRelationConfig>
	</a-modal>
</template>


<style scoped></style>
